package clients

import (
	"QWenVL/models"
	"QWenVL/services"
	"context"
	"encoding/json"
	"fmt"

	"github.com/sagikazarmark/slog-shim"
)

type QwenRequestBody struct {
	ApiKey string `header:"Authorization"`
	Imgurl string `query:"img-url"`
	Body   models.RequestBody
}

func QwenVLhandler(c context.Context, input *QwenRequestBody) (*string, error) {

	headers := make(map[string]string)
	headers["Content-Type"] = "application/json"
	headers["Authorization"] = "Bearer" + input.ApiKey
	// headers["X-DashScope-SSE"] = "enable"
	result, err := services.CallQwenVLAPI(headers, &input.Body)

	if err != nil {
		slog.Error("Error calling Qwen-VL API:", "Error", err)
		return nil, err
	}
	var response models.Response
	err = json.Unmarshal([]byte(result), &response)
	if err != nil {
		slog.Error("响应体解码出错", "Error", err)
		return nil, err
	}

	return &response.Output.Choices[0].Message.Content[0].Text, nil

}

type UploadImgInput struct {
	ApiKey string `header:"Authorization"`
	// FileDir string `query:"FileDir"`
	Body models.FormData
}

func UploadImgHandler(c context.Context, input *UploadImgInput) (*string, error) {

	// 现在你可以使用formData中的字段
	// 例如，保存文件到服务器
	if input.Body.File != nil {

		// 保存文件到服务器的文件系统
		// ...
		// if r.Method == "POST" {
		// if !strings.Contains(r.Header.Get("Content-Type"), "multipart/form-data") {
		// 	// 不支持的 Content-Type 类型
		// 	fmt.Println("Invalid Content-Type: ", r.Header.Get("Content-Type"))
		// 	return nil,nil
		// }
		// 限制上传文件的大小为5MB
		var filesMax int64 = 5 << 20

		// 整个请求的主体大小设置为7.5Mb
		r.Body = http.MaxBytesReader(w, input.Body, filesMax)
		err := r.ParseMultipartForm(filesMax)
		if err != nil {
			fmt.Fprintln(w, "服务端："+err.Error(), http.StatusBadRequest)
			fmt.Println("服务端："+err.Error(), http.StatusBadRequest)
			return nil,err
		}
		// 获取上传的文件
		file, header, err := r.FormFile("file")
		if err != nil {
			fmt.Fprintln(w, "服务端：error retreiving file")
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Printf("Uploaded File: %+v\n", header.Filename)
		fmt.Printf("File Size: %+v\n", header.Size)
		fmt.Printf("MIME Type: %+v\n", header.Header.Get("Content-Type"))
		// 将文件保存到服务器指定的目录（* 用来随机数的占位符）
		fileBytes, err := ioutil.ReadAll(file)
		if err != nil {
			fmt.Fprintln(w, "服务端：", err)
			return nil,err
		}
		//创建文件
		newFile, err := os.Create("uploads/" + header.Filename)
		if err != nil {
			fmt.Fprintln(w, "服务端：", err)
			return nil,err
		}
		defer func() {
			_ = newFile.Close()
		}()
		newFile.Write(fileBytes)
		fmt.Fprintf(w, "Successfully Uploaded File\n")
		// return nil,err
	}
	// http.NotFound(w, r)
	}
	// 上传文件到代理服务器
	var localfile  string
	localfile = "uploads/" + header.Filename
	ImgUrl, err := services.UploadImgDirParse(localfile)
	if err != nil {
		slog.Error("文件上传时解析出错", "Error", err)
		return nil, nil
	}

	var imgurl models.UploadImgUrl
	err = json.Unmarshal([]byte(ImgUrl), &imgurl)
	if err != nil {
		slog.Error("响应体解码出错", "Error", err)
		return nil, err
	}

	// input.Body.Input.Messages[0].Content[0].Image = imgurl.ImgUrl
	body := &models.RequestBody{

		Model: "qwen-vl-plus",
		Input: models.InputBody{
			Messages: []models.Message{
				{
					Role: "user",
					Content: []models.Content{
						{
							Image: ImgUrl,
							Text:  "",
						},
						{
							Image: "",
							Text:  "这个图片是哪里？",
						},
					},
				},
			},
		},
		Parameters: "",
	}

	headers := make(map[string]string)
	headers["Content-Type"] = "application/json"
	headers["Authorization"] = "Bearer" + input.ApiKey
	// headers["X-DashScope-SSE"] = "enable"
	result, err := services.CallQwenVLAPI(headers, body)

	if err != nil {
		fmt.Println("Error calling Qwen-VL API:", err)
		return nil, err
	}
	var response models.Response
	err = json.Unmarshal([]byte(result), &response)
	if err != nil {
		slog.Error("响应出错", "Error", err)
		return nil, err
	}

	return &response.Output.Choices[0].Message.Content[0].Text, nil
}
